package com.geek.thread.base;

import com.geek.util.UnSafeUtil;

/**
 * 指令重排序以及内存屏障
 */
public class CmdSort {

	public int a, b;
	public int x, y;

	public static void main(String[] args) throws InterruptedException {
		CmdSort obj = new CmdSort();
		obj.test();
	}

	/**
	 * 因为指令重排序的缘故，可能会出现x=0，y=0的情况
	 * 解决办法：使用volatile修饰变量添加内存屏障
	 * 解决办法二：使用UnSafe添加内存屏障
	 * @throws InterruptedException
	 */
	public void test() throws InterruptedException {
		int count = 0;
		while (true){
			a = 0;
			b = 0;
			Thread t1 = new Thread(() -> {
				a = 1;
//				UnSafeUtil.getInstance().fullFence();
				x = b;
			});
			Thread t2 = new Thread(() -> {
				b = 1;
//				UnSafeUtil.getInstance().fullFence();
				y = a;
			});

			t1.start();
			t2.start();
			t1.join();
			t2.join();

			if(x == 0 && y == 0){
				System.out.println("第"+(++count)+"次执行,x="+x+",y="+y);
				break;
			}else{
				System.out.println("第"+(++count)+"次执行,x="+x+",y="+y);
			}
		}
	}

}

